import React, { useMemo, useState, useEffect, useRef } from 'react'
import { Input, Popover, Divider, Spin, Tag, Typography } from 'antd';
import { h5Utils } from '@inbiz/utils';
import cn from 'classnames';
import InbizGraph from '../../InbizGraph';
import { InbizIcon } from '@inbiz/utils';
import { getMessage } from '@inbiz/react'
import SearchImgPanel from '../../SmallPanelView/SearchImgPanel';
import PanelContainer from '../PanelContainer'
import LabelConfigSelect from '../../SearchView/LabelConfigSelect';
import { useSearchUIState } from '../../../../../store/hooks/useSearchUIState';
import { useSearchUIDispatch } from '../../../../../store/hooks/useSearchUIDispatch';
import { SearchResultPanel } from '../../SearchResultPanel';
import { useConfigEventsApi } from '../../../../../store/hooks/useSearchPropsState';
import './index.less'
export default function SmallPanelInput(props) {
  const {
    indexRange,
    onSearchChange,
    onSearchFocus,
    onSearch,
    placeholderText,
    stop,
    $visible,
    visible,
    inputwidth,
    smallPanelViewInputClassName,
    $fullScreen,
    $uploadData,
    hoverIndex,
    clearStorage,
    searchMessage,
    customFolderId,
    inbiz,
    interactiveMethods,
    $customPlaceholderText
  } = props
  const searchInput = useRef<any>(null);
  const divRef = useRef<HTMLDivElement>(null)
  const [loading, $loading] = useState(false)
  const { selectShowTab, showSearchResultPanel, keyword, showGraph, showFullModal, showTag } = useSearchUIState();
  const updateUIState = useSearchUIDispatch();
  const { configEvents } = useConfigEventsApi();
  const imageShotSearchText = getMessage('SearchEngine.imageShot')

  const contentView = useMemo(() => {
    if (visible) {
      return <SearchImgPanel divRef={divRef} $visible={$visible} visible={visible} onOk={(data: any) => {
        $uploadData({ ...data });
      }} />
    } else if (showGraph) {
      return <PanelContainer>
        <InbizGraph customHeight={460} customWidth={inputwidth} svgBoxId='popoverSvg' />
      </PanelContainer>
    } else if (showSearchResultPanel) {
      return <PanelContainer>
        <SearchResultPanel hoverIndex={hoverIndex} $loading={$loading} smallPanelViewInputClassName={smallPanelViewInputClassName} $fullScreen={$fullScreen} />
      </PanelContainer>
    }
    return null
  }, [visible, showSearchResultPanel, hoverIndex, showGraph, showFullModal])


  const closeTag = (e) => {
    e.stopPropagation()
    searchInput.current?.focus()
    $customPlaceholderText(getMessage('SearchEngine.search'))
    updateUIState({
      showTag: false
    });
  }
  const tagComponent = useMemo(() => {
    if (searchMessage.title) {
      return <Tag className='closeTag'>
        <Typography.Text style={{ maxWidth: 70 }} ellipsis title={searchMessage.title}>
          {searchMessage.title}
        </Typography.Text>
        <InbizIcon
          onClick={closeTag}
          type="icon-ic-close-bold"
          style={{color: '#666', fontSize: 14}}
        />
      </Tag>
    }
    return null
  }, [searchMessage])
  useEffect(() => {
    if (!keyword || !showSearchResultPanel || showGraph) {
      $loading(false)
    }
  }, [keyword, showSearchResultPanel, showGraph])

  const inputKeydown = (e) => {
    if (e.keyCode === 40 || e.keyCode === 38) {
      e.preventDefault()
    } else if (e.keyCode === 8 && !keyword) {
      $customPlaceholderText('')
      updateUIState({
        showTag: false
      });
    }
  }
  
  return (
    <Popover
      overlayClassName='smallViewPopover'
      overlayStyle={{
        width: inputwidth,
        maxHeight: 500,
      }}
      autoAdjustOverflow={false}
      getPopupContainer={() => document.body}
      placement='bottom'
      content={<Spin spinning={loading && showSearchResultPanel}>
        <div onClick={() => {
          h5Utils.inbizPageEvent.emit(props.controlId, true);
        }}>
          {contentView}
        </div>
      </Spin>}
      visible={showSearchResultPanel || visible}
    // visible={true}
    >
      {/** 这个div只是为了在有焦点,panel又被关闭的时候,再次点输入框,panel再显示出来 */}
      <div
        ref={divRef}
      >
        {/** 宽度 599 */}
        <Input
          className={cn('search-input-control')}
          addonBefore={Boolean(indexRange) && <LabelConfigSelect smallPanelViewInputClassName={props.smallPanelViewInputClassName} tagComponent={tagComponent} />}
          size="large"
          ref={searchInput}
          maxLength={40}
          onChange={onSearchChange}
          onFocus={onSearchFocus}
          autoFocus={!interactiveMethods || interactiveMethods == 'defaultWidth'}
          onPressEnter={(e) => {
            onSearch(e.target.value, false)
            if (e.target.value) {
              searchInput.current?.blur?.();
            }
          }}
          onKeyDown={inputKeydown}
          value={keyword}
          placeholder={visible ? imageShotSearchText : placeholderText}
          onBlur={() => updateUIState({
            // showSearchResultPanel: false,
          })}
          suffix={
            <span className="search-handles">
              {keyword && keyword !== '' && (
                <InbizIcon
                  type="icon-ic-close-bold"
                  className="all-clear-action"
                  onMouseDown={(e) => {
                    e.stopPropagation()
                    e.preventDefault()
                  }}
                  onClick={() => {
                    updateUIState({ panelId: 'historySearch', keyword: '', });
                    clearStorage()
                    configEvents.current?.onCustomClear?.()
                    setTimeout(() => {
                      searchInput.current?.focus?.();
                    }, 0)
                  }}
                />
              )}
              <Divider type="vertical" style={{ height: 16, background: '#eee', marginRight: 10 }} />
              {selectShowTab?.keywordAtlas && keyword && keyword !== '' ? (
                <InbizIcon
                  type="icon-atlas-hover"
                  title={getMessage('SearchEngine.inform')}
                  onMouseDown={() => {
                    stop.current = true;
                  }}
                  onClick={() => {
                    $visible(false);
                    $loading(false)
                    updateUIState({ showSearchResultPanel: true, showGraph: true, })
                  }}
                />
              ) : selectShowTab?.imgSearchImg 
                && (!customFolderId || (customFolderId !='7' && customFolderId != inbiz.userInfo.topPersonalFolderId) || !showTag) ? (
                //【v7】团队库和个人库打开搜索时，不要显示图文搜索按钮,当搜索框团队库/个人库回显的搜索目录被删除时，可以回显搜图按钮
                <InbizIcon
                  type="icon-ico-Searchforpictures"
                  onMouseDown={() => {
                    stop.current = true;
                  }}
                  title={getMessage('SearchEngine.imgSearchImg')}
                  onClick={(e: any) => {
                    e.stopPropagation();
                    e.preventDefault();
                    $loading(false)
                    $visible(true);
                  }}
                />
              ) : null}
              {/* 【v7】团队库和个人库不支持高级搜索 */}
              {selectShowTab?.advancedSearch && 
              (!customFolderId || (customFolderId !='7' && customFolderId != inbiz.userInfo.topPersonalFolderId) || !showTag) &&
              <InbizIcon
                type="icon-sousuokuang-gaojisousuo"
                onMouseDown={() => {
                  stop.current = true;
                }}
                title={getMessage('SearchEngine.advancedSearch')}
                onClick={(e) => {
                  e.stopPropagation()
                  $visible(false);
                  $loading(false)
                  updateUIState({
                    showSearchResultPanel: true,
                    panelId: 'advancedSearch',
                    showGraph: false
                  });
                }}
              />}
              {props.searchIcon.type && <InbizIcon
                type={props.searchIcon.type}
                onMouseDown={() => {
                  stop.current = true;
                }}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation()
                  e.preventDefault();
                  onSearch(keyword, false)
                }}
              />}
            </span>
          }
        />
      </div>
    </Popover>
  )
}
